#include <assert.h>
#include "event_loop_thread.h"
#include "event_loop.h"

void *event_loop_thread_run(void *arg)
{
    struct event_loop_thread *loop_thread = (struct event_loop_thread *)arg;

    pthread_mutex_lock(&loop_thread->mutex);

    // 初始化 event_loop 并通知主线程
    loop_thread->eloop = event_loop_init_with_name(loop_thread->thread_name);
    pthread_cond_signal(&loop_thread->cond);

    pthread_mutex_unlock(&loop_thread->mutex);

    // 运行子线程的 event_loop
    event_loop_run(loop_thread->eloop);
}

int event_loop_thread_init(struct event_loop_thread *loop_thread, int i)
{
    pthread_mutex_init(&loop_thread->mutex, NULL);
    pthread_cond_init(&loop_thread->cond, NULL);
    loop_thread->eloop = NULL;
    loop_thread->thread_count = 0;
    loop_thread->thread_tid = 0;

    char *buf = malloc(16);
    sprintf(buf, "Thread-%d\0", i + 1); // 线程名称
    loop_thread->thread_name = buf;

    return 0;
}

struct event_loop *event_loop_thread_start(struct event_loop_thread *loop_thread)
{
    pthread_create(&loop_thread->thread_tid, NULL, &event_loop_thread_run, loop_thread);

    assert(pthread_mutex_lock(&loop_thread->mutex));
    // 循环等待创建成功
    while (loop_thread->eloop == NULL)
    {
        pthread_cond_wait(&loop_thread->cond, &loop_thread->mutex);
    }
    assert(pthread_mutex_unlock(&loop_thread->mutex) == 0);
    return loop_thread->eloop;
}